package edu.npu.cv.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import edu.npu.cv.constant.ResultCode;
import edu.npu.cv.dao.MemberDAO;
import edu.npu.cv.entity.MemberDO;
import edu.npu.cv.entity.PageDO;
import edu.npu.cv.entity.ResultDO;
import edu.npu.cv.service.MemberService;
import edu.npu.cv.utils.PageQueryUtil;
import edu.npu.cv.vo.MemberVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * @author lelechang
 * @description: 服务层
 * @version: V1.0
 */
@Service
@Transactional
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDAO memberDao;

    /**
     * 从数据库中获取成员列表
     *
     * @return
     */
    public List<MemberDO> findAll() {
        return memberDao.selectList(new QueryWrapper<MemberDO>());
    }

    /**
     * 根据ID查询实体
     *
     * @param id
     * @return
     */
    public MemberDO findById(long id) {
        return memberDao.selectById(id);
    }

    @Override
    public ResultDO<PageDO> findAll(PageQueryUtil pageQueryUtil) {
        List<MemberDO> memberDOS = memberDao.getMembers(pageQueryUtil);
        int total = getMemberCount();
        return new ResultDO<PageDO>(true, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS,
            new PageDO(total, pageQueryUtil.getLimit(), pageQueryUtil.getPage(),
                MemberVO.transMemberDOs2VOs(memberDOS)));
    }

    @Override
    public int getMemberCount() {
        return memberDao.selectCount(null).intValue();
    }

    @Override
    public ResultDO<Void> saveMember(MemberDO memberDO) {
        return memberDao.insert(memberDO) > 0 ? new ResultDO<>(true, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS)
            : new ResultDO<>(false, ResultCode.DB_ERROR, ResultCode.MSG_DB_ERROR);
    }

    @Override
    public ResultDO<Void> updateMember(MemberDO memberDO) {
        return memberDao.updateById(memberDO) > 0 ? new ResultDO<>(true, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS)
            : new ResultDO<>(false, ResultCode.DB_ERROR, ResultCode.MSG_DB_ERROR);
    }

    @Override
    public ResultDO<Void> deleteBatch(Long[] ids) {
        int result = memberDao.deleteBatchIds(Arrays.asList(ids));
        if (result > 0) {
            return new ResultDO<>(true, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS);
        } else {
            return new ResultDO<>(false, ResultCode.DB_ERROR, ResultCode.MSG_DB_ERROR);
        }
    }

}
